<template>
  <div class="app-container">
    <div :style="drawerShow ? 'width: calc(100% - 600px);' : 'width: 100%;'">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="100px"
      >
        <el-form-item>
          <el-button type="primary" plain size="mini" @click="batchAcquire(1)"
            >批量取药</el-button
          >
          <el-button
            type="success"
            plain
            size="mini"
            @click="batchDispensing(1)"
            >批量发送配药机</el-button
          >
        </el-form-item>
        <el-form-item label="关键词" prop="searchValue">
          <el-input
            v-model="queryParams.searchValue"
            placeholder="订单编号/消费人/开方医生"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 215px"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单支付时间">
          <el-date-picker
            v-model="createTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            @change="handleQuery"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        ref="singleTable"
        :data="tableList"
        v-loading="loading"
        style="width: 100%"
        highlight-current-row
        @current-change="handleCurrentChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          label="姓名"
          prop="parescriptOrder.patientName"
          align="center"
          width="120"
          fixed="left"
        ></el-table-column>
        <el-table-column
          label="性别"
          prop="parescriptOrder.patientSex"
          align="center"
          width="80"
        >
          <template slot-scope="{ row }">
            <div v-if="row.parescriptOrder">
              {{ row.parescriptOrder.patientSex === 1 ? "女" : "男" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="年龄"
          prop="parescriptOrder.patientAge"
          align="center"
          width="80"
        >
          <template slot-scope="{ row }">
            <div v-if="row.parescriptOrder">
              {{ row.parescriptOrder.patientAge }}岁
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="联系方式"
          prop="parescriptOrder.patientPhone"
          align="center"
          width="150"
        ></el-table-column>
        <el-table-column
          label="支付时间"
          prop="playCreateTime"
          align="center"
          width="180"
        ></el-table-column>
        <el-table-column label="开方时间" align="center" width="180">
          <template slot-scope="{ row }">
            <span>{{
              row.parescriptOrder
                ? row.parescriptOrder.applyDate
                : row.createTime
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="开方医生"
          prop="sponsor"
          align="center"
          width="120"
        ></el-table-column>
        <el-table-column
          min-width="150"
          label="订单所属渠道"
          prop="channelName"
        ></el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <div v-show="drawerShow" class="drawerBox">
      <div class="disFlxJS mb-5">
        <div class="fz-16 fw-6">
          <span> 订单号（{{ info.orderNo }}） </span>
          <span
            v-if="getMedicationStatusTitle(info)"
            class="ml-10"
            :style="{ color: getMedicationStatusTitle(info).color }"
          >
            ({{ getMedicationStatusTitle(info).title }})
          </span>
        </div>
        <div @click="closeDrawer">
          <i class="iconfont el-icon-circle-close fz-24 color9 cup" />
        </div>
      </div>

      <div class="disFlx linh-24">
        <div class="flexShrink">诊断证型：</div>
        <div>
          {{
            info.parescriptOrder
              ? info.parescriptOrder.typesResult
              : info.initialDiagn
          }}
        </div>
      </div>

      <template v-if="info.parescriptOrder">
        <div class="disFlx linh-24">
          <div class="flexShrink">患者主诉：</div>
          <div>{{info.parescriptOrder.patientPrincipal}}</div>
        </div>
        <div class="disFlx linh-24">
          <div class="flexShrink">物流备注：</div>
          <div v-if="info.parescriptOrder.sendPrescript === 1" class="colorRED">{{ "需随药发处方单" }}</div>
        </div>
        <div class="disFlx linh-24">
          <div class="flexShrink">药房备注：</div>
          <div>{{info.parescriptOrder.pharmacyRemark}}</div>
        </div>
      </template>

      <div class="disFlx linh-24">
        <div class="flexShrink">收货信息：</div>
        <div>{{ getShippingAddress(info) }}</div>
      </div>

      <el-card class="mt-20">
        <div class="girdBox">
          <div
            v-for="(item, index) in info.sheetList"
            :key="index"
            class="printOrder fz-14"
          >
            <ParescriptNum :info="info" :serviceDetailIndex="index" />
            <div class="disFlxJS pt-10 pb-5">
              <div
                v-if="
                  info.parescriptOrder &&
                  (info.parescriptOrder.status === 0 ||
                    info.parescriptOrder.status === 1 ||
                    info.parescriptOrder.status === 3)
                "
                class="fw-7 colorRED"
              >
                {{
                  info.parescriptOrder.status === 0
                    ? "配药机接收中"
                    : "已发送配药机"
                }}
              </div>
              <div v-else></div>
              <div>
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-printer"
                  @click="print(item, index)"
                  >打印预览</el-button
                >
                <el-button
                  v-if="
                    info.parescriptOrder &&
                    info.parescriptOrder.status !== 0 &&
                    (!info.parescriptOrder.status ||
                      info.parescriptOrder.status === -1 ||
                      info.parescriptOrder.status === 2)
                  "
                  type="success"
                  size="mini"
                  @click="batchDispensing(0)"
                  >发送配药机</el-button
                >
                <el-button
                  v-if="
                    info.parescriptOrder &&
                    info.parescriptOrder.status !== -1 &&
                    info.parescriptOrder.status !== 3
                  "
                  type="success"
                  size="mini"
                  @click="batchAcquire(0)"
                  >确认取药</el-button
                >
              </div>
            </div>
            <ParescriptType :info="info" :prescriptionInfo="item"  class="my-5">
              <div
                v-if="info.parescriptOrder && info.parescriptOrder.status === 3"
                class="disFlx py-3"
              >
                <span class="fw-7 shrink0">是否取药：</span>
                <span style="color: #67c23a">(已取药)</span>
              </div>
              <div
                v-else-if="
                  info.parescriptOrder && info.parescriptOrder.status !== -1
                "
                class="disFlx py-3"
              >
                <span class="fw-7 shrink0">是否取药：</span>
                <span class="pl-10" style="color: #f56c6c">(未取药)</span>
              </div>
              <div v-if="info.orderSource != 1" class="disFlx py-3">
                <span class="fw-7 shrink0">小计：</span>
                <span
                  ><span class="fw-6 colorY">{{ item.subCost }}</span>
                  云豆</span
                >
              </div>
            </ParescriptType>

            <ParescriptItem
              :info="info"
              :prescriptionInfo="item"
              :printConfig="printConfig"
            />
          </div>
        </div>
      </el-card>
    </div>


    <div style="display: none">
      <div ref="printOrder">
        <PrintDom
          :info="info"
          :printConfig="printConfig"
          :prescriptionInfo="prescriptionInfo"
          :serviceDetailIndex="serviceDetailIndex"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {
  getMedicationList,
  prescriptionDrugTake,
  pushPrescription,
} from "@/api/order/waitMedicine.js";
import { getMedicationStatusTitle, getShippingAddress } from '../components/mixin.js'
import { Print } from "@/utils/print";
import PrintDom from '../components/print.vue'
import ParescriptNum from '../components/prescription/num.vue'
import ParescriptType from '../components/prescription/type.vue'
import ParescriptItem from '../components/prescription/item.vue'

export default {
  name: "WaitMedicine",
  components: {
    PrintDom,
    ParescriptNum,
    ParescriptType,
    ParescriptItem
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      createTime: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchValue: "",
        playCreateTimegt: "", // 开始时间
        playCreateTimelt: "", // 结束时间
      },
      tableList: [],
      drawerShow: false,
      info: {}, // 当前选中行
      prescriptionInfo: null,
      serviceDetailIndex: 0, // 处方号所在的下标
      printConfig: {},
    };
  },
  created() {
    this.getList();
  },
  activated() {
    this.getList();
  },
  methods: {
    getMedicationStatusTitle,
    getShippingAddress,
    async getList() {
      this.queryParams.playCreateTimegt =
        this.createTime && this.createTime.length ? this.createTime[0] : "";
      this.queryParams.playCreateTimelt =
        this.createTime && this.createTime.length ? this.createTime[1] : "";
      const response = await getMedicationList(this.queryParams);
      this.tableList = response.rows;
      this.total = response.total;
      this.loading = false;
      if (this.tableList.length) {
        this.handleCurrentChange(this.tableList[0]);
      } else {
        this.closeDrawer();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createTime = [];
      this.handleQuery();
    },
    // 批量取药 是否批量:  0单个处理（需要orderId,prescriptOrderId ） 1批量处理（需要orderIds）
    batchAcquire(isBatch) {
      if (isBatch === 1) {
        if (!this.$refs.singleTable.selection.length) {
          this.$message.error("请选择要取药的数据");
          return;
        }
        prescriptionDrugTake({
          isBatch,
          orderIds: this.$refs.singleTable.selection.map((v) => v.id),
        }).then(() => {
          this.$message.success("批量取药成功");
          this.handleQuery();
          this.closeDrawer();
        });
      } else {
        prescriptionDrugTake({
          isBatch,
          orderId: this.info.id,
          prescriptOrderId: this.info.parescriptOrder.id,
        }).then(() => {
          this.$message.success("处方取药成功");
          this.handleQuery();
          this.closeDrawer();
        });
      }
    },
    // 批量发送配药机
    batchDispensing(isBatch) {
      if (isBatch === 1) {
        if (!this.$refs.singleTable.selection.length) {
          this.$message.error("请选择要发送配药机的数据");
          return;
        }
        pushPrescription({
          isBatch,
          orderIds: this.$refs.singleTable.selection.map((v) => v.id),
        }).then(() => {
          this.$message.success("数据已发送，配药机接收中");
          this.getList();
        });
      } else {
        pushPrescription({
          isBatch,
          orderId: this.info.id,
          prescriptOrderId: this.info.parescriptOrder.id,
        }).then(() => {
          this.$message.success("数据已发送，配药机接收中");
          this.getList();
        });
      }
    },

    // 表格选中切换
    handleCurrentChange(row) {
      this.$refs.singleTable.setCurrentRow(row);
      this.info = row;
      this.drawerShow = true;
    },
    // 关闭弹窗
    closeDrawer() {
      this.$refs.singleTable.setCurrentRow();
      this.info = {};
      this.drawerShow = false;
    },
    print(item, index) {
      this.prescriptionInfo = item;
      this.serviceDetailIndex = index;

      const printConfig = localStorage.getItem("printConfig");
      this.printConfig = printConfig ? JSON.parse(printConfig) : {};

      this.$nextTick(() => {
        Print(this.$refs.printOrder);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  position: relative;
}
.drawerBox {
  position: absolute;
  top: 0;
  right: 0;
  border-left: solid 1px #e5e5e5;
  width: 600px;
  height: calc(100vh - 84px);
  padding: 10px;
  font-size: 14px;
  overflow-y: auto;
}
.flexShrink {
  flex-shrink: 0;
}
.prescriptionBox {
  background-color: #e1f3d8;
  padding: 10px;
  margin-top: 10px;
}
.colorRED {
  color: #f56c6c;
}
.colorY {
  color: #bb9313;
}

.grid3 {
  display: grid;
  gap: 10px 5px;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  div {
    text-align: center;
  }
}
</style>
